package com.phonemap.models;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.phonemap.common.Util;

public class Relationship {

	public static Entity createOrUpdateRelationship(String name) {
		Entity relationship = Relationship.getSingleRelationship(name);
		if (relationship == null) {
			relationship = new Entity("Relationship", name);
			relationship.setProperty("relationship", name);
		
		} else {
			relationship.setProperty("relationship", name);
		}
		Util.persistEntity(relationship);
		return relationship;
	}

	public static Entity getSingleRelationship(String name) {
		Iterable<Entity> results = Util.listEntities("Relationship", "relationship", name);
		List<Entity> entity = new ArrayList<Entity>();
		for (Entity e : results)
			if (e != null)
				entity.add(e);
		if (!entity.isEmpty()) {
			return (Entity) entity.remove(0);
		}
		return null;
	}

	public static Iterable<Entity> getAllRelationships() {
		Iterable<Entity> entities = Util.listEntities("Relationship", null, null);
		return entities;
	}
	
	public static Iterable<Entity> getAllRelationships(String kind) {
		Iterable<Entity> entities = Util.listEntities(kind, null, null);
		return entities;
	}

	public static Iterable<Entity> getRelationship(String relationship) {
		Iterable<Entity> entities = Util.listEntities("Relationship", "relationship", relationship);
		return entities;
	}
}
